<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\Sms;
use app\models\ContactForm;

class SiteController extends Controller {

	public function behaviors() {
		return [
			'access' => [
				'class' => AccessControl::className(),
				'only' => ['logout'],
				'rules' => [
					[
						'actions' => ['logout'],
						'allow' => true,
						'roles' => ['@'],
					],
				],
			],
			'verbs' => [
				'class' => VerbFilter::className(),
				'actions' => [
					'logout' => ['post'],
				],
			],
		];
	}

	public function actions() {
		return [
			'error' => [
				'class' => 'yii\web\ErrorAction',
			],
			'captcha' => [
				'class' => 'yii\captcha\CaptchaAction',
				'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
			],
		];
	}

	public function actionIndex() {
		return $this->render('index');
	}

	public function actionLogin() {
		if (!\Yii::$app->user->isGuest) {
			return $this->goHome();
		}

		$model = new LoginForm();
		if ($model->load(Yii::$app->request->post()) && $model->login()) {
			return $this->goBack();
		} else {
			return $this->render('login', [
					'model' => $model,
			]);
		}
	}

	public function actionLogout() {
		Yii::$app->user->logout();

		return $this->goHome();
	}

	public function actionContact() {
		$model = new ContactForm();
		if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
			Yii::$app->session->setFlash('contactFormSubmitted');

			return $this->refresh();
		} else {
			return $this->render('contact', [
					'model' => $model,
			]);
		}
	}

	public function actionAbout() {
		return $this->render('about');
	}

	public function beforeAction($action) {
		$this->enableCsrfValidation = false;
		return parent::beforeAction($action);
	}
	
	public function actionImport() {
		if (Yii::$app->request->getIsPost()) {
			$uploadFile = $_FILES['message']['tmp_name'];
			$xml = simplexml_load_file($uploadFile);
			$imported = 0;
			foreach ($xml->sms as $node) {
				$sms = new Sms();
				$sms->attributes = current($node->attributes());
				$sms->readable_date = date('Y-m-d H:i:s', $sms->date/1000);
				if ($sms->contact_name == '(Unknown)')
					$sms->contact_name = $sms->address;

				$imported += $sms->save();
			}
			Yii::$app->session->setFlash("success", "Imported $imported record(s).");
		}
		return $this->render('import');
	}

	public function actionView() {
		$year = '2014';
		$month = '10';
		
	}
}
